package cn.com.tuns.assess.qsb.frame.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import cn.com.tuns.assess.qsb.frame.ui.AppManage;
import cn.com.tuns.assess.qsb.frame.ui.Config;
import cn.com.tuns.assess.qsb.frame.ui.MyApplication;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class LogUtil {

    public static final String TAG = "LogUtil";

    /**
     * 收集设备参数信息
     *
     * @param ctx
     */
    public static Map<String, String> collectDeviceInfo(Context ctx) {
        Map<String, String> infos = new HashMap<String, String>();
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),
                    PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null"
                        : pi.versionName;
                String versionCode = pi.versionCode + "";
                infos.put("versionName", versionName);
                infos.put("versionCode", versionCode);

                String x5CrashInfo = com.tencent.smtt.sdk.WebView.getCrashExtraMessage(ctx);
                infos.put("x5crashInfo", x5CrashInfo);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, e.toString());
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                infos.put(field.getName(), field.get(null).toString());
                // Log.d(TAG, field.getName() + " : " + field.get(null));
            } catch (Exception e) {
                Log.e(TAG, e.toString());
            }
        }

        return  infos;
    }

    /**
     * 保存错误信息到文件中
     *
     * @param ex
     * @return 返回文件名称, 便于将文件传送到服务器
     */
    public synchronized static String saveCrashInfo2File(Throwable ex) {
        Date date=new Date();
        Map<String, String> infos=collectDeviceInfo(MyApplication.context);

        StringBuffer sb = new StringBuffer();
        sb.append("=========loginfo\n");
        sb.append("logdate=" + DateUtils.dateToString(date,DateUtils.BzFormat))
                .append("\n");
//        sb.append("ip=" + TrSetData.APP_HTTP_URL);
//        sb.append("|");
//        sb.append("user=" + TrSetData.USER_NAME);
//        sb.append("|");
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "|");
        }
        sb.append("\n");

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result);
        sb.append("\n");

        try {
            // long timestamp = System.currentTimeMillis();
            String time = DateUtils.dateToString(date,DateUtils.YmdFormat);
            String fileName = time + ".log";

            String path = AppManage.getSysLogPath();
            File dir = new File(path,fileName);

            FileOutputStream fos = new FileOutputStream(dir,
                    true);
            fos.write(sb.toString().getBytes());
            fos.close();

            return fileName;
        } catch (Exception e) {
            Log.e(TAG,  e.toString());
        }
        return null;
    }

    /**
     * 保存错误信息到文件中
     *
     * @return 返回文件名称, 便于将文件传送到服务器
     */
    public synchronized static void saveLogString(String str) {
        Date date = new Date();
        Map<String, String> infos = collectDeviceInfo(MyApplication.context);

        StringBuffer sb = new StringBuffer();
        sb.append("=========loginfo\n");
        sb.append("logdate=" + DateUtils.dateToString(date, DateUtils.BzFormat))
                .append("\n");
        sb.append(str).append("\n");

        FileOutputStream fos =null;
        try {
            // long timestamp = System.currentTimeMillis();
            String time = DateUtils.dateToString(date,DateUtils.YmdFormat);
            String fileName = time + ".log";

            String path = AppManage.getSysLogPath();
            File dir = new File(path,fileName);

            fos=new FileOutputStream(dir,
                    true);
            fos.write(sb.toString().getBytes());

        } catch (Exception e) {
            Log.e(TAG,  e.toString());
        }
        finally {
            if(fos!=null)
            {
                try {
                    fos.close();
                }
                catch (Exception e)
                {

                }
            }
        }
    }

    /**
     * 上传所有日志
     */
    public static void postAllErrorLog(){
        if(AndroidUtils.isApkInDebug(MyApplication.context))
        {
            return;
        }
        String path=AppManage.getSysLogPath();;
        File root=new File(path);
        File[] files=root.listFiles();
        String today=DateUtils.dateToString(new Date(),DateUtils.YmdFormat);
        ArrayList<File> fileList=new ArrayList<>();
        for(File f:files)
        {
            if(f.isFile())
            {
                String mdate=f.getName();
                mdate=mdate.substring(0,mdate.lastIndexOf("."));
//                String mdate=DateUtils.dateToString(new Date(f.lastModified()),DateUtils.YmdFormat);

                if(today.compareTo(mdate)>0)
                {
                    fileList.add(f);
                }

            }
        }
        if(fileList.size()>0)
            postReport(fileList);
    }

    private static void postReport(final ArrayList<File> fileList) {
        new Thread(){
            @Override
            public void run() {
                String url= Config.getUpdateLogUrl();
                for(File f:fileList){
                    String errorContent = FileUtil.getContentFromFile(f.getPath());
                    HashMap<String,String> hashMap=new HashMap<>();
                    hashMap.put("log",errorContent);
                    if(TextUtils.isEmpty(AppManage.phone))
                    {
                        hashMap.put("userId",AppManage.phone);
                    }
                    else {
                        hashMap.put("userId","-1");
                    }
                    String json=new Gson().toJson(hashMap);
                    OkHttpUtil okHttpUtil=new OkHttpUtil();
                    String str=okHttpUtil.syncPost(url,json);
                    if(!TextUtils.isEmpty(str))
                    {
                        Type type= new TypeToken<HashMap<String,String>>() {}.getType();
                        HashMap<String,String> baseBean=new Gson().fromJson(str, type);
                        int code=StrUtil.nullToInt(baseBean.get("code"));
                        if(code==0)
                        {
                            f.delete();
                        }
                    }

                }
            }
        }.start();




//        ExceptionLogReq req = new ExceptionLogReq();
//        ExceptionLog info = new ExceptionLog();
//        if (localUserInfo != null && localUserInfo.getAuthority() != null) {
//            req.setHead(localUserInfo.getAuthorityHead());
//            if (StringUtils.isValid(localUserInfo.getAuthority().getUser().getUserId())) {
//                info.setUserId(localUserInfo.getAuthority().getUser().getUserId());
//            } else {
//                info.setUserId("-1");
//            }
//            info.setLog(errorContent);
//
//        } else {
//            AuthorityHead authorityHead = new AuthorityHead();
//            authorityHead.setVersion(AndroidUtils.getVersionName(getApplicationContext()));
//
//            authorityHead.setSystem("Android");
//            String deviceUUid = MyCrashHanlder.getDeviceUUid();
//            if (StringUtils.isValid(deviceUUid)) {
//                deviceUUid = deviceUUid.replaceAll("-", "");
//            } else {
//                deviceUUid = "noCreatUUId";
//            }
//            //设备的UUID
//            authorityHead.setDeviceId(deviceUUid);
//            //请求ID用 UUID
//            authorityHead.setRequestId(UUID.randomUUID().toString().replaceAll("-", ""));
//            authorityHead.setTokenId("");
//            req.setHead(authorityHead);
//
//            info.setUserId("-1");
//            info.setLog(errorContent);
//        }
//        req.setBody(info);
//
//        new HttpRequestTask<BaseRsp>(AppContext.applicationContext, req, "3") {
//            @Override
//            protected void onSuccess(BaseRsp rsp) {
//                super.onSuccess(rsp);
//                file.delete();
//                Log.e("错误日志上传", "上传成功");
//            }
//
//            @Override
//            protected void onError(BaseRsp rsp) {
//                super.onError(rsp);
//                Log.e("错误日志上传", "上传成功");
//            }
//        }.runRequestCode();

    }


    public static String getOplogPath(){
        File file=new File(AppManage.getRootPath(),"oplog");
        if(!file.exists())
        {
            file.mkdirs();
        }
        return file.getAbsolutePath();
    }

    /**
     * 保存错误信息到文件中
     *
     * @return 返回文件名称, 便于将文件传送到服务器
     */
    public synchronized static void saveOplogString(String str) {
        Date date = new Date();
        String userId=TextUtils.isEmpty(AppManage.phone)?"-1":AppManage.phone;

        StringBuffer sb = new StringBuffer();
        sb.append("=========loginfo\n");
        sb.append("logdate=" + DateUtils.dateToString(date, DateUtils.BzFormat))
                .append("\n");
        sb.append("userId=" + userId)
                .append("\n");
        sb.append(str).append("\n");

        FileOutputStream fos =null;
        try {
            // long timestamp = System.currentTimeMillis();
            String time = DateUtils.dateToString(date,DateUtils.YmdFormat);
            String fileName = time + ".log";

            String path = getOplogPath();
            File dir = new File(path,fileName);

            fos=new FileOutputStream(dir,
                    true);
            fos.write(sb.toString().getBytes());

        } catch (Exception e) {
            Log.e(TAG,  e.toString());
        }
        finally {
            if(fos!=null)
            {
                try {
                    fos.close();
                }
                catch (Exception e)
                {

                }
            }
        }
    }

    public static void deleteOpLog(){
        String path = getOplogPath();
        File[] files=new File(path).listFiles();
        Date date=DateUtils.addDays(new Date(),-7);
        String time=DateUtils.dateToString(date,DateUtils.YmdFormat);
        for(File f:files)
        {
            if(f.isFile())
            {
                String mdate=f.getName();
                mdate=mdate.substring(0,mdate.lastIndexOf("."));
            }
        }
    }



    public static  void shareLog(Activity activity)
    {
        String root=AppManage.getRootPath();
        String zipName="tmp.zip";
        String zipPath=new File(root,zipName).getAbsolutePath();
        try {
            ZipUtil.ZipFolder(root,zipPath,new String[]{zipName});
            AndroidShareUtil.shareLogFile(activity,zipPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
